<!--  -->
<template>
  <div class>
    <el-upload action="http://admin.npwh.com:88/api/member/upload/uploadfile"
               list-type="picture"
               :multiple="false"
               :show-file-list="showFileList"
               :file-list="fileList"
               :before-upload="beforeUpload"
               :on-remove="handleRemove"
               :on-success="handleUploadSuccess"
               :on-preview="handlePreview">
      <el-button size="small"
                 type="primary">点击上传</el-button>
      <div slot="tip"
           class="el-upload__tip">只能上传jpg/png文件，且不超过10MB</div>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%"
           :src="fileList[0].url"
           alt />
    </el-dialog>
  </div>
</template>

<script>
// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
// 例如：import 《组件名称》 from '《组件路径》';

export default {
  name: 'singleUpload',
  props: {
    value: String,
    imgUrl: String
  },
  watch: {
    value (newVal, oldVal) {
      // console.log('value>newVal=' + newVal)
      // console.log('value>oldVal=' + oldVal)
    }
  },
  computed: {
    imageUrl () {
      return this.value
    },
    imageName () {
      if (this.value != null && this.value !== '') {
        let spl = this.value.split('/')
        return spl[spl.length - 2] + '/' + spl[spl.length - 1]
        // return this.value.substr(this.value.lastIndexOf('/') + 1)
      } else {
        return null
      }
    },
    fileList () {
      return [{
        name: this.imageName,
        url: this.imageUrl
      }]
    },
    showFileList: {
      get: function () {
        return this.value !== null && this.value !== '' && this.value !== undefined
      },
      set: function (newValue) {
      }
    }
  },
  data () {
    // 这里存放数据
    return {
      dialogVisible: false
    }
  },
  // 方法集合
  methods: {
    emitInput (val) {
      this.$emit('input', val)
    },
    // 上传文件之前的钩子
    beforeUpload (file) {
      let allowSuffix = ['image/jpeg', 'image/png']
      let isAllow = allowSuffix.find(elem => elem === file.type)
      const isLt2M = file.size / 10240 / 10240 < 10

      if (!isAllow) {
        this.$message.error('上传头像图片只能是 JPG、PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 10MB!')
      }
      // return isJPG && isLt2M
      return isAllow && isLt2M
    },
    // 删除文件之前的钩子
    handleRemove (file, fileList) {
      this.emitInput('')
    },
    // 点击文件列表中已上传的文件时的钩子
    handlePreview (file) {
      this.dialogVisible = true
    },
    // 文件上传成功时的钩子
    handleUploadSuccess (res, file) {
      // console.log('上传成功...')
      this.showFileList = true
      this.fileList.pop()
      this.fileList.push({ name: file.name, url: res.data.imageUrl })
      this.emitInput(this.fileList[0].url)
    }
  }
}
</script>
<style scoped>
</style>